import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final TextEditingController _qqController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _nicknameController = TextEditingController();
  bool _obscureText = true;

  // 本地头像资源
  final List<String> _avatarPaths = [
    'images/avatar.jpg',
    'images/1.jpg',
    'images/2.jpg',
    'images/3.jpg',
    'images/4.jpg',
    'images/5.jpg',
    'images/6.jpg',
    'images/7.jpg',
    'images/8.jpg',
    'images/9.jpg',
    'images/10.jpg',
    'images/11.jpg',
    'images/12.jpg',
  ];
  String? _selectedAvatar;

  @override
  void initState() {
    super.initState();
    _selectedAvatar = _avatarPaths[0]; // 默认选中第一个头像
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('注册QQ'),
        centerTitle: true,
        backgroundColor: Colors.blue,
      ),
      body: SingleChildScrollView( // 上下滚动
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text("选择头像:", style: TextStyle(fontSize: 16)),
              const SizedBox(height: 8),
              SizedBox(
                height: 100, // 固定高度
                child: ListView.builder(
                  scrollDirection: Axis.horizontal, // 水平滑动
                  itemCount: _avatarPaths.length,
                  itemBuilder: (context, index) {
                    final path = _avatarPaths[index];
                    final isSelected = path == _selectedAvatar;
                    return GestureDetector(
                      onTap: () {
                        setState(() {
                          _selectedAvatar = path;
                        });
                      },
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 8.0),
                        child: CircleAvatar(
                          radius: 40,
                          backgroundColor:
                          isSelected ? Colors.blue : Colors.grey[300],
                          child: CircleAvatar(
                            radius: 35,
                            backgroundImage: AssetImage(path),
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ),
              const SizedBox(height: 20),
              const Text("QQ号:", style: TextStyle(fontSize: 16)),
              const SizedBox(height: 8),
              TextField(
                controller: _qqController,
                decoration: const InputDecoration(
                  hintText: '请输入QQ号',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.number,
              ),
              const SizedBox(height: 10),
              const Text("密码:", style: TextStyle(fontSize: 16)),
              const SizedBox(height: 8),
              TextField(
                controller: _passwordController,
                decoration: InputDecoration(
                  hintText: '请输入密码',
                  border: const OutlineInputBorder(),
                  suffixIcon: IconButton(
                    icon: Icon(
                      _obscureText ? Icons.visibility : Icons.visibility_off,
                    ),
                    onPressed: () {
                      setState(() {
                        _obscureText = !_obscureText;
                      });
                    },
                  ),
                ),
                obscureText: _obscureText,
              ),
              const SizedBox(height: 10),
              const Text("昵称:", style: TextStyle(fontSize: 16)),
              const SizedBox(height: 8),
              TextField(
                controller: _nicknameController,
                decoration: const InputDecoration(
                  hintText: '请输入昵称',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: _register,
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size(double.infinity, 50),
                  backgroundColor: Colors.blue,
                ),
                child: const Text('注册',
                    style: TextStyle(fontSize: 18, color: Colors.white)),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _register() async {
    final prefs = await SharedPreferences.getInstance();
    final qq = _qqController.text;
    final password = _passwordController.text;
    final nickname = _nicknameController.text;

    if (qq.isEmpty || password.isEmpty || nickname.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请完整填写所有信息')),
      );
      return;
    }

    if (prefs.containsKey('qq_$qq')) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('该QQ号已被注册')),
      );
      return;
    }

    if (_selectedAvatar == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请选择头像')),
      );
      return;
    }

    // 保存用户信息
    await prefs.setString('qq_$qq', password);
    await prefs.setString('nickname_$qq', nickname);
    await prefs.setString('avatar_$qq', _selectedAvatar!);

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('注册成功')),
    );

    // 返回登录界面并携带昵称和头像路径
    Navigator.pop(context, {'qq': qq, 'nickname': nickname, 'avatar': _selectedAvatar!});
  }

}
